const path = require('path'),
    resolve = dir => path.resolve(__dirname, dir),
    IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV),
    BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin,
    CompressionWebpackPlugin = require('compression-webpack-plugin'),
    productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
    express = require('express'),
    UglifyJsPlugin = require('uglifyjs-webpack-plugin'),
    CSSSplitWebpackPlugin = require('css-split-webpack-plugin'),
    ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin'),
    FileManagerPlugin = require('filemanager-webpack-plugin'),
    proxyConfig = require('./proxyConfig');


module.exports = {
    transpileDependencies: ['webpack-dev-server/client'],
    // 基本路径
    publicPath: './',
    // 输出文件目录
    outputDir: 'dist',
    // eslint-loader 是否在保存的时候检查
    lintOnSave: false,
    assetsDir: '',                           //    相对于outputDir的静态资源(js、css、img、fonts)目录
    runtimeCompiler: true,                   //    是否使用包含运行时编译器的 Vue 构建版本
    // 生产环境是否生成 sourceMap 文件
    productionSourceMap: false,

    chainWebpack: config => {

        config.entry.app = ['babel-polyfill', './src/main.js'];
        // 修复HMR
        config.resolve.symlinks(true);
        //修复 Lazy loading routes Error
        config.plugin('html').tap(args => {
            args[0].chunksSortMode = 'none';
            return args;
        });
        // 添加别名
        config.resolve.alias
            .set('@', resolve('src'))
            .set('assets', resolve('src/assets'))
            .set('components', resolve('src/components'))
            .set('layout', resolve('src/layout'))
            .set('base', resolve('src/base'))
            .set('static', resolve('src/static'));
        // 打包分析
        if (process.env.IS_ANALYZ) {
            config.plugin('webpack-report')
                .use(BundleAnalyzerPlugin, [{
                    analyzerMode: 'static',
                }]);
        }
        // 打包图片压缩处理
        const imagesRule = config.module.rule("images")
        imagesRule
            .use('url-loader')
            .loader('url-loader')
            .tap(options => Object.assign(options, { limit: 6144 }));

    },

    configureWebpack: config => {
        if (IS_PROD) {
            const plugins = [];
            //开启 gzip 压缩
            plugins.push(
                new CompressionWebpackPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: productionGzipExtensions,
                    threshold: 10240,
                    minRatio: 0.8
                })
            );
            //    plugins.push(new CSSSplitWebpackPlugin({ size: 3000 }));
            plugins.push(
                new ParallelUglifyPlugin({
                    cacheDir: '.cache/',
                    uglifyJS: {
                        output: {
                            comments: false
                        }
                    }
                })
            )
            plugins.push(
                new FileManagerPlugin({  //初始化 filemanager-webpack-plugin 插件实例
                    onEnd: {
                        delete: [   //首先需要删除项目根目录下的dist.zip
                            './dist.zip',
                        ],
                        archive: [ //然后我们选择dist文件夹将之打包成dist.zip并放在根目录
                            { source: './dist', destination: './dist/dist.zip' },
                        ]
                    }
                })
            )
            // 如果是生产环境 去掉 console
            if (process.env.NODE_ENV === 'production') {
                config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true;
            }
            config.plugins = [
                ...config.plugins,
                ...plugins
            ];
        }
    },
    // css相关配置
    css: {
        // extract: true,       //    extract:true的这一条配置，注释掉之后就可以自动更新
        sourceMap: false,
        loaderOptions: {
            css: { importLoaders: 1 },
            less: { importLoaders: 1 }
        },
        modules: false

    },
    parallel: require('os').cpus().length > 1,
    pwa: {},
    devServer: {
        open: true,
        host: 'localhost',
        port: 8080,
        https: false,
        hotOnly: false,
        proxy: null,     // 设置代理
        before: app => {
            // 配置静态目录
            app.use(
                "/static",
                express.static(path.resolve(__dirname, "public/"))
            )

        }
    },

    // 第三方插件配置
    pluginOptions: {

    }

};